package com.douyu.water.core.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.douyu.water.core.PagePara;
import com.douyu.water.core.dao.MenuMapper;
import com.douyu.water.core.dao.RoleMapper;
import com.douyu.water.core.dao.UserMapper;
import com.douyu.water.core.model.Menu;
import com.douyu.water.core.model.MenuExample;
import com.douyu.water.core.model.Role;
import com.douyu.water.core.model.RoleMenuKey;
import com.douyu.water.core.model.RoleExample;
import com.douyu.water.core.model.UserExample;
import com.douyu.water.util.Func;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired 
	private MenuMapper menuMapper;
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public List<Role> select(Role record, PagePara page) {
		List<Role> list = null;
		RoleExample example = createExample(record);
		if(page != null)
		{
			int total = roleMapper.countByExample(example);
			page.setTotal(total);
			example.setPagePara(page);
		}
		list = roleMapper.selectByExample(example);
		return list;
	}

	@Override
	public int insert(Role record) {
		int flag = 0;
		if(record == null)
		{
			return flag;
		}
		if(!checkRole(record))
		{
			return 2;
		}
		String newid = Func.getNewId();
		record.setUcode(newid);
		flag = roleMapper.insert(record);
		return flag;
	}

	@Override
	public int update(Role record) {
		int flag = 0;
		if(record == null || StringUtils.isBlank(record.getUcode()))
		{
			return flag;
		}
		if(!checkRole(record))
		{
			return 2;
		}
		flag = roleMapper.updateByPrimaryKey(record);
		return flag;
	}

	@Override
	public int delete(String record) {
		int flag = 0;
		if(StringUtils.isBlank(record))
		{
			return flag;
		}
		if(this.checkUse(record))
		{
			return 2;
		}
		flag = roleMapper.deleteByPrimaryKey(record.trim());
		return flag;
	}

	@Override
	public int updateAuth(RoleMenuKey rm) {
		int flag = 0;
		if(rm == null || StringUtils.isBlank(rm.getMenucode()) || StringUtils.isBlank(rm.getRolecode()))
		{
			return flag;
		}
		List<RoleMenuKey> list = null;
		String roleCode = rm.getRolecode();
		String menuCodes = rm.getMenucode();
		if(menuCodes != null)
		{
			list = createListRole(roleCode,menuCodes);
		}
		for (RoleMenuKey r : list) {
			System.out.println(r.getMenucode()+","+r.getRolecode());
		}
		int a=deleteRoleAuth(roleCode);
		System.out.println(a);
		flag = roleMapper.insertBatch(list);
		return flag;
	}

	/**
	 * 删除角色权限
	 * @param roleCode Stirng
	 * @return
	 */
	private int deleteRoleAuth(String roleCode)
	{
		int flag = 0;
		if(StringUtils.isBlank(roleCode))
		{
			return flag;
		}
		flag = roleMapper.deleteAuth(roleCode.trim());
		return flag;
	}
	@Override
	public Role view(String ucode)
	{
		Role role = null;
		if(StringUtils.isBlank(ucode))
		{
			return role;
		}
		role = roleMapper.selectByPrimaryKey(ucode.trim());
		return role;
	}
	
	@Override
	public List<Menu> selectMenu(String roleCode){
		if(StringUtils.isBlank(roleCode))
		{
			return null;
		}
		//检索功能列表
		Menu funcMenu = new Menu();
		funcMenu.setUtype("1");
		List<Menu> func = this.selectMenu(funcMenu);
		
		if(func != null && func.size() > 0)
		{
			int size = func.size();
			//获取操作功能
			for(int i = 0;i < size;i++)
			{
				Menu temp = func.get(i);
				//检查有没有已经分配
				checked(temp,roleCode);
				String parent = temp.getUcode();
				Menu child = new Menu();
				child.setParent(parent.trim());
				child.setUtype("2");
				List<Menu> op = this.selectMenu(child);
				checked(op,roleCode);
				if(op != null && op.size() > 0)
				{
					temp.setChild(op);
				}
				
			}
		}
		return func;
	}
	
	/**
	 * 检索是否已经分配
	 * @param obj
	 * @param role
	 */
	private void checked(Object obj,String role)
	{
		if(obj == null || StringUtils.isBlank(role))
		{
			return;
		}
		List<String> check = roleMapper.selectCheckMenu(role.trim());
		if(obj instanceof Menu){
			String code = ((Menu) obj).getUcode();
			if(check.contains(code.trim()))
			{
				((Menu) obj).setChecked(true);
			}
		}
		else if(obj instanceof List)
		{
			process((List<Menu>)obj,check);
		}
	}
	
	/**
	 * 检索列表是否已经分配
	 * @param list
	 * @param check
	 */
	private void process(List<Menu> list,List<String> check){
		if(list == null || list.size() == 0
				|| check == null || check.size() == 0)
		{
			return;
		}
		for(Menu temp : list){
			String code = temp.getUcode();
			if(check.contains(code.trim())){
				temp.setChecked(true);
			}
		}
	}
	/**
	 * 根据条件检索系统功能菜单
	 * @param record
	 * @return
	 */
	private List<Menu> selectMenu(Menu record)
	{
		List<Menu> list = null;
		MenuExample example = createMenuExample(record);
		list = menuMapper.selectByExample(example);
		return list;
	}
	/**
	 * 形成菜单查询条件
	 * @param record
	 * @return
	 */
	private MenuExample createMenuExample(Menu record)
	{
		MenuExample example = new MenuExample();
		MenuExample.Criteria criteria = example.createCriteria();
		if(record != null)
		{
			if(!StringUtils.isBlank(record.getUtype()))
			{
				criteria.andUtypeEqualTo(record.getUtype().trim());
			}
			if(!StringUtils.isBlank(record.getParent()))
			{
				criteria.andParentEqualTo(record.getParent().trim());
			}
			
		}
		example.setOrderByClause(" isort asc");
		return example;
	}
	/**
	 * 形成批量记录的列表
	 * @param roleCode String  
	 *        -角色编号
	 * @param menuCodes String 
	 *        -菜单编号
	 * @return List<RoleMenuKey>
	 */
	private List<RoleMenuKey> createListRole(String roleCode,String menuCodes)
	{
		List<RoleMenuKey> list = null;
		if(StringUtils.isBlank(roleCode))
		{
			return list;
		}
		String[] codes = menuCodes.trim().split("[, ]+");
		if(codes.length == 0)
		{
			return list;
		}
		list = new ArrayList<RoleMenuKey>();
		int len = codes.length;
		for(int i = 0;i < len;i++)
		{
			if(!StringUtils.isBlank(codes[i]))
			{
				list.add(new RoleMenuKey(roleCode,codes[i].trim()));
			}
		}
		return list;
	}
	/**
	 * 检查角色是否正在使用
	 * @param role Role
	 * @return
	 */
	private boolean checkUse(String role)
	{
		boolean flag = true;
		if(StringUtils.isBlank(role))
		{
			return flag;
		}
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		criteria.andRoleLike("%"+ role.trim()+"%");
		int cnt = userMapper.countByExample(example);
		if(cnt == 0)
		{
			flag = false;
		}
		return flag;
	}
	/**
	 * 检测角色名称是否重复
	 * @param role Role
	 * @return boolean
	 */
	private boolean checkRole(Role role)
	{
		boolean flag = true;
		if(role == null || StringUtils.isBlank(role.getUname()))
		{
			flag = false;
		}
		RoleExample example = new RoleExample();
		RoleExample.Criteria criteria = example.createCriteria();
		criteria.andUnameEqualTo(role.getUname().trim());
		if(!StringUtils.isBlank(role.getUcode()))
		{
			criteria.andUcodeNotEqualTo(role.getUcode().trim());
		}
		int cnt = roleMapper.countByExample(example);
		if(cnt > 0)
		{
			flag = false;
		}
		return flag;
	}
	/**
	 * 根据角色形成检索条件
	 * @param record Role
	 * @return RoleExample
	 */
	private RoleExample createExample(Role record)
	{
		RoleExample example = new RoleExample();
		RoleExample.Criteria criteria = example.createCriteria();
		criteria.andUcodeIsNotNull();
		if(record != null)
		{
			if(!StringUtils.isBlank(record.getUname()))
			{
			   criteria.andUnameLike("%" + record.getUname().trim() + "%");	
			}
			if(!StringUtils.isBlank(record.getUcode()))
			{
				criteria.andUcodeEqualTo(record.getUcode().trim());
			}
		}
		return example;
	}
}
